import styles from "./index.module.less";
import defaultHead from "@images/sex0.webp";
import { request } from "@apis/request";

function Operate(doms) {
    // 需要用到的dom
    this.doms = doms;
    // 游戏区高度
    this.gameHeight = 568;
    // 背景图的初始位置
    this.bgStartX = 0;
    // 背景图移动速度
    this.bgSpeed = 5;
    // 小鸟距离顶部的初始距离
    this.initTop = 188;
    // 小鸟距离顶部的最大距离
    this.maxTop = 536;
    // 是否上升状态
    this.isUp = false;
    // 小鸟移动速度，初始速度为0
    this.birdSpeed = 0;
    // 小鸟最大速度
    this.maxSpeed = 6;
    // 小鸟下降的加速度
    this.downA = 0.4;
    // 小鸟上升的加速度
    this.upA = 0.7;
    // 定时器timer 初始值null
    this.timer = null;
    // 定时器延时
    this.delay = 50;
    // 水平方向相邻两个管道之间相隔多少个管道的距离
    this.distance = 120;
    // 管道计数
    this.pipeCount = 0;
    // 开始插入管道的横向位置
    this.firstPipeX = 320;
    // 上下管道的间隔距离
    this.pipeSpace = 120;
    // 管道宽度
    this.pipeWidth = 62;
    // 管道移动速度
    this.pipeSpeed = 2;
    // 游戏得分 初始为0
    this.score = 0;

    // 生成范围内随机数
    this.range = function (min, max) {
        return Math.round(Math.random() * (max - min) + min);
    };
    // 判断碰撞
    this.isCrash = function (pipe) {
        const { bird } = this.doms;
        var l1 = pipe.offsetLeft;
        var t1 = pipe.offsetTop;
        var r1 = l1 + pipe.offsetWidth;
        var b1 = t1 + pipe.offsetHeight;

        var l2 = bird.offsetLeft;
        var t2 = bird.offsetTop;
        var r2 = l2 + bird.offsetWidth;
        var b2 = t2 + bird.offsetHeight;
        if (r2 < l1 || b2 < t1 || r1 < l2 || b1 < t2) {
            // 不碰撞
            return false;
        } else {
            // 碰撞
            return true;
        }
    };
}

/**背景图移动 */
Operate.prototype.bgMove = function () {
    const { bg } = this.doms;
    this.bgStartX -= this.bgSpeed;
    bg.style.backgroundPositionX = this.bgStartX + "px";
};

/**小鸟移动 */
Operate.prototype.birdMove = function (isSpaceUp) {
    const { bird } = this.doms;
    if (isSpaceUp) {
        this.birdSpeed = -this.maxSpeed;
        this.isUp = true;
    }
    if (bird.offsetTop <= 0 || bird.offsetTop >= this.maxTop) {
        this.gameOver();
        return;
    }
    if (this.isUp) {
        bird.children[0].className = `${styles.bird} ${styles.up}`;
        this.birdSpeed += this.upA;
        if (this.birdSpeed >= 0) {
            this.birdSpeed = 0;
            this.isUp = false;
        }
    } else {
        bird.children[0].className = `${styles.bird} ${styles.down}`;
        this.birdSpeed += this.downA;
        this.birdSpeed = Math.min(this.birdSpeed, this.maxSpeed);
    }
    bird.style.top = bird.offsetTop + this.birdSpeed + "px";
};

/**创建管道 */
Operate.prototype.createPipe = function () {
    const { ul } = this.doms;
    this.pipeCount++;
    if (this.pipeCount !== this.distance) return;
    this.pipeCount = 0;
    const pipeHeight = this.range(100, 300);
    const pipeDom = `
    <li class="top_pipe"
      style="height: ${pipeHeight}px; left: ${this.firstPipeX}px;"
      
    >
      <div class="pipe_head"></div>
    </li>
    <li class="bottom_pipe"
      style="height: ${
          this.gameHeight - pipeHeight - this.pipeSpace
      }px; left: ${this.firstPipeX}px"
    >
      <div class="pipe_head"></div>
    </li>
  `;
    ul.insertAdjacentHTML("beforeend", pipeDom);
};

/**管道移动 */
Operate.prototype.pipeMove = function () {
    const { ul, score } = this.doms;
    this.createPipe(ul);
    const lis = document.querySelectorAll("li");
    lis.forEach((item, index, arr) => {
        arr[index].style.left = arr[index].offsetLeft - this.pipeSpeed + "px";
        if (arr[index].offsetLeft <= -this.pipeWidth) {
            arr[index].remove();
            // 注意这里，因为每次通过的是上下两个对称的管道，所以自增会执行两次
            this.score++;
            // 所以这里得分应该除以2
            score.innerHTML = this.score / 2 + "分";
        }
    });
};

/**检查碰撞 */
Operate.prototype.check = function () {
    const _this = this;
    const lis = document.querySelectorAll("li");
    lis.forEach((item) => {
        if (_this.isCrash(item)) {
            _this.gameOver();
        }
    });
};

/**开始游戏 */
Operate.prototype.start = function () {
    const { begin, play } = this.doms;
    begin.style.display = "none";
    play.style.display = "block";
    this.timer = setInterval(() => {
        this.bgMove();
        this.birdMove(false);
        this.pipeMove();
        this.check();
    }, this.delay);
};

/**游戏结束 */
Operate.prototype.gameOver = function () {
    const { end, result } = this.doms;
    clearInterval(this.timer);
    end.style.display = "block";
    result.innerHTML = this.score / 2;
    this.getBest();
};

/**游戏结束时获取最高分纪录 */
Operate.prototype.getBest = async function () {
    const { img, best } = this.doms;
    const res = await request("/getBirdBest");
    console.log("res: ", res);
    if (res.code === "0000") {
        img.src = require(`@images/head/${res.data.avatarUrl}`);
        best.innerHTML = res.data.best || "暂无";
    } else {
        img.src = defaultHead;
        best.innerHTML = "?";
    }
};

/**数据初始化 */
Operate.prototype.init = async function () {
    const { bg, bird, ul, score, result, best, img, begin, play, end } =
        this.doms;
    if (this.score > 0) {
        await request("/addBestScore", { score: this.score / 2 }, "post");
    }
    this.bgStartX = 0;
    bg.style.backgroundPositionX = "0px";
    this.isUp = false;
    this.birdSpeed = 0;
    this.timer = null;
    this.pipeCount = 0;
    ul.innerHTML = "";
    bird.style.top = this.initTop + "px";
    this.score = 0;
    score.innerHTML = "0分";
    result.innerHTML = 0;
    best.innerHTML = 0;
    img.src = defaultHead;
    begin.style.display = "block";
    play.style.display = "none";
    end.style.display = "none";
};

export default Operate;
